import {
  Controller,
  Get,
  Post,
  Body,
  Patch,
  Param,
  Delete,
} from '@nestjs/common';
import { BookService } from './book.service';
import { CreateBookDto } from './dto/create-book.dto';
import { UpdateBookDto } from './dto/update-book.dto';

@Controller('book')
export class BookController {
  constructor(private readonly bookService: BookService) {}

  //抛出异常中断服务程序，测试docker的自动重启
  // @Post()
  // throwAError(){
  //   throw new Error('error')
  // }
  
  @Post()
  async create(@Body() createBookDto: CreateBookDto) {
    try {
      await this.bookService.create(createBookDto);
      return {
        code: 0,
        msg: 'ok',
      };
    } catch (e) {
      //返回400状态码
      return {
        code: -1,
        msg: e.message,
      };
    }
  }
  @Post('list')
  async list(@Body() listBookDto: any) {
    try {
      let data = await this.bookService.list(listBookDto);
      return {
        code: 0,
        msg: 'ok',
        data
      };
    } catch (e) {
      //返回400状态码
      return {
        code: -1,
        msg: e.message,
      };
    }
  }

  @Post('chat')
  async chat(@Body() req: any) {
    try {

      let data = await this.bookService.chat(req);
      if(!data){
        throw new Error('服务器波动，请重试')
      }
      return {
        code: 0,
        msg: 'ok',
        data
      };
    } catch (e) {
      console.log(e)
      //返回400状态码
      return {
        code: -1,
        msg: e.message,
      };
    }
  }
  @Get()
  findAll() {
    return this.bookService.findAll();
  }

  @Get(':id')
  findOne(@Param('id') id: string) {
    return this.bookService.findOne(+id);
  }

  @Patch(':id')
  update(@Param('id') id: string, @Body() updateBookDto: UpdateBookDto) {
    return this.bookService.update(+id, updateBookDto);
  }

  @Delete(':id')
  remove(@Param('id') id: string) {
    return this.bookService.remove(+id);
  }
}
